from django.shortcuts import render
from rest_framework.views import APIView
# Create your views here.
from home.tools.SendMessageTools import send_message
from home.tools.RedisTools import r
from rest_framework.response import Response
import re
import random
from home.models import *
from home.tools.JWTTools import g
import time

class SendMessageView(APIView):
    def post(self,request):
        # 输入手机号，
        phone=request.data.get("phone")
        print(phone)
        # 校验手机号发送验证码,【通过redis防止多次发送验证码】
        re_phone=re.match(r"^1[3-9]\d{9}$",phone)
        if(re_phone):
            if(r.get_str(phone)):
                return Response({"message": "验证码已经发送，请耐心等待", "code": 1001})
            else:
                code=random.randint(1000,9999)
                result=send_message(phone,code)
                if(result):
                    r.setex_str(phone,code,3600)
                    return Response({"message": "手机号发送成功", "code": 1000})
                else:
                    return Response({"message": "手机号验证码发送失败","code":1001})
        else:
            return Response({"message":"手机号校验失败","code":1001})


class LoginView(APIView):
    def post(self,request):
        # 输入验证码和手机号，并比较校验码
        phone = request.data.get("phone")
        code = request.data.get("code")

        code_red=str(r.getex_str(phone))
        if(code):
            print(type(code))
            print(type(code_red))
            print(code == code_red)
            if (code == code_red):
                user=UserModel.objects.filter(phone__exact=phone).first()
                if(user):
                    u1=UserModel()
                    u1.name=phone
                    u1.phone=phone
                    u1.save()
                info={
                    "name":user.name if (user) else phone ,
                    "phone": user.phone if (user) else phone,
                    "exp":int(time.time())+3600
                }
                token=g.jwt_encode(info)

                user = UserModel.objects.filter(phone__exact=phone).first()
                role = RoleModel.objects.filter(id=user.role.id).first()
                roleid = role.id
                role1 = RoleModel.objects.filter(id=roleid).first()
                rolelist = role1.source.all()
                viewlist=[]
                interfacelist=[]
                for i in rolelist:
                    viewlist.append(i.url)
                    list = i.interfaceurl.all()
                    for i in list:
                        interfacelist.append(i.url)

                r.set_srt("user" + str(user.id) + "interface", json.dumps(interfacelist))
                return Response({"message": "登录成功", "code": 1000,"token":token,"menulist":json.dumps(viewlist)})

            else:
                return Response({"message": "code值输入的不正确", "code": 1001})



        # 通过jwt生成用户的token
        # 同时也要进行用户数据的保存
        # 并进行页面跳转，让前端存储token，并让拦截其能够使得每个请求带上token
        else:
            return Response({"message": "手机号未发送验证码", "code": 1001})

from django.db.models import Q
from home.ser.Serilze import *
class MenuView(APIView):
    def get(self,request):
        #查询用户角色，然后展示对应的资源

        roleid=request.GET.get("roleid")
        #先获取全部的菜单权限
        listall=ResourceModel.objects.filter(pid__isnull=False).all()
        allres = [{"key": i.id, 'label': i.name} for i in listall]
        # listalldata=ResourceSer(instance=allres,many=True)
        #获取该用户下的菜单
        query = Q()
        if roleid:
            # 如果有搜索条件，构建查询
            query = Q(source=roleid)
        listsome=ResourceModel.objects.filter(query).all()
        checkedids = [i.id for i in listsome]


        return Response({"message": "11", "all":allres,"some":checkedids })

    def post(self,request):
        roleid = request.data.get("roleid")
        idlist = request.data.get("idlist")
        role1=RoleModel.objects.filter(id=roleid).first()
        print(role1.source)
        role1.source.clear()
        role1.source.add(*idlist)
        return Response({"code": 200})




class RoleView(APIView):
    def get(self,request):
        roles=RoleModel.objects.all()
        roledata=RoleSer(roles,many=True)
        return Response({"message": "11", "rlist": roledata.data})
import json
class LoginRoleView(APIView):
    def get(self,request):
        token = request.headers.get("token")
        info = g.jwt_decode(token)
        userphone = info.get("phone")
        user = UserModel.objects.filter(phone__exact=userphone).first()
        role = RoleModel.objects.filter(id=user.role.id).first()
        roleid = role.id
        role1 = RoleModel.objects.filter(id=roleid).first()

        rolelist=role1.source.all()


        roleinfolist=[]
        idlist=[]
        interfacelist=[]
        for i in rolelist:

            if(not  i.pid):
                idlist.append(i.pid)
                roleinfolist.append({"id": i.id,"label":i.name,"children":[]})

            list=i.interfaceurl.all()
            for i in list:
                interfacelist.append(i.url)

        for j,index in enumerate(roleinfolist):
            print(j)
            print(index)
            for i in rolelist:
                print(type(i.pid))
                print(type(index["id"]))
                if(i.pid is not None and i.pid.id==index["id"]):

                    roleinfolist[j]["children"].append({"id":i.id,"label":i.name,"url":i.url})
        # print(user.id)
        # r.set_srt("user"+str(user.id)+"interface",json.dumps(interfacelist))
        return Response({'code':200,"datalist":roleinfolist})


